<?php

namespace App\Models;


use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;

/**
 * Class Dorm.
 *
 * @package namespace App\Models;
 */
class Dorm extends BaseModel implements Transformable
{
    use TransformableTrait;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['company_id', 'building_id', 'dorm_type_id', 'floor', 'code', 'unit_name', 'beds', 'bed_rent', 'rent', 'for_gender', 'status', 'remark'];

    public function building()
    {
        return $this->belongsTo(Building::class);
    }

    public function staffs()
    {
        return $this->hasMany(Staff::class);
    }

    public function dormType()
    {
        return $this->belongsTo(DormType::class);
    }

    public function activeWaterMeter()
    {
        return $this->hasOne(DormMeter::class)->where('meter_type_id', 1)->where('active', 1);
    }
    public function activeHotWaterMeter()
    {
        return $this->hasOne(DormMeter::class)->where('meter_type_id', 3)->where('active', 1);
    }

    public function activeElectricMeter()
    {
        return $this->hasOne(DormMeter::class)->where('meter_type_id', 2)->where('active', 1);
    }

    public function meters()
    {
        return $this->hasMany(DormMeter::class);
    }

    public function activeMeters()
    {
        return $this->hasMany(DormMeter::class)->where('active', 1);
    }

    public function scopeAvailableDorms(Builder $query, $staff)
    {
        return $query->with('building:id,name', 'dormType:id,name', 'staffs')
            ->whereHas('dormType', function ($q) use ($staff) {
                $q->whereIn('staff_position_id', [$staff->staff_position_id, 0])
                    ->whereIn('for_gender', [$staff->sex, 0]);
                //                ->orWhereNull('staff_position_id')
                //                ->orWhereNull('for_gender');
            })->withCount('staffs');
    }

    public function scopeShouldInstallMeter(Builder $builder)
    {
        return $builder->whereHas('dormType.electricFeeType', function ($q) {
            $q->where('compute_unit', '元/计量单位');
        });
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (auth()->check()) {
                $model->company_id = auth()->user()->company_id ?? null;
            }
        });
    }
}
